package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.leyou.item.entity.Category;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandServiceImpl categoryBrandService;


    @Override  //根据父类目id查询子类目的集合
    public List<CategoryDTO> findCategoryByid(Long pid) {
        List<Category> categories = query().eq("parent_id", pid).list();
        return CategoryDTO.convertEntityList(categories);
    }

    @Override  //根据id查询分类
    public CategoryDTO queryCategoryById(Long id) {
        Category category = query().eq("parent_id", id).one();
        return new CategoryDTO(this.getById(id));
    }

    @Override  //根据品牌id查询分类
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        // 1.根据品牌id，查询中间表，得到中间表对象集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();

        //判断查询的集合是否为空
        if (CollectionUtils.isEmpty(categoryBrandList)) {
            //返回一个空的List集合 但是该集合没有实现删除添加等方法
            return Collections.emptyList();
        }

        //方法:抽取List<Long>集合中所有对象的CategoryId
        // 2.获取分类id集合
        List<Long> categoryIdList = categoryBrandList.stream()
                .map(CategoryBrand::getCategoryId).collect(Collectors.toList());


        // 3.根据分类id集合，查询分类对象集合
        List<Category> categories = listByIds(categoryIdList);
        // 4.转换DTO
        return CategoryDTO.convertEntityList(categories);
    }


    /*//分页模板
    public List<Object>  pagexx(Integer page ,Integer rows,Service key){
      // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);
        // 5.封装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));

    }*/
}



